import BaseDTO from './BaseDTO.js';

/**
 * UserDTO - 用户数据传输对象
 * 处理用户相关的数据验证、转换和格式化
 */
class UserDTO extends BaseDTO {
    constructor(data = {}) {
        super(data);
        this.initializeRules();
    }

    /**
     * 初始化用户验证规则
     */
    initializeRules() {
        // 用户创建验证规则
        this.createRules = {
            username: {
                required: true,
                type: 'string',
                minLength: 3,
                maxLength: 50,
                pattern: /^[a-zA-Z0-9_]+$/,
                custom: (value) => {
                    if (value && /^[0-9]/.test(value)) {
                        return 'Username cannot start with a number';
                    }
                    return true;
                }
            },
            email: {
                required: true,
                type: 'email',
                maxLength: 255
            },
            password: {
                required: true,
                type: 'string',
                minLength: 6,
                maxLength: 128,
                custom: (value) => {
                    if (value && !/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
                        return 'Password must contain at least one lowercase letter, one uppercase letter, and one number';
                    }
                    return true;
                }
            },
            full_name: {
                required: false,
                type: 'string',
                maxLength: 100
            },
            phone: {
                required: false,
                type: 'string',
                pattern: /^[\+]?[1-9][\d]{0,15}$/
            },
            age: {
                required: false,
                type: 'integer',
                min: 13,
                max: 120
            },
            gender: {
                required: false,
                type: 'string',
                enum: ['male', 'female', 'other']
            },
            status: {
                required: false,
                type: 'string',
                enum: ['active', 'inactive', 'suspended'],
                default: 'active'
            }
        };

        // 用户更新验证规则（所有字段都是可选的）
        this.updateRules = {
            username: {
                required: false,
                type: 'string',
                minLength: 3,
                maxLength: 50,
                pattern: /^[a-zA-Z0-9_]+$/,
                custom: (value) => {
                    if (value && /^[0-9]/.test(value)) {
                        return 'Username cannot start with a number';
                    }
                    return true;
                }
            },
            email: {
                required: false,
                type: 'email',
                maxLength: 255
            },
            full_name: {
                required: false,
                type: 'string',
                maxLength: 100
            },
            phone: {
                required: false,
                type: 'string',
                pattern: /^[\+]?[1-9][\d]{0,15}$/
            },
            age: {
                required: false,
                type: 'integer',
                min: 13,
                max: 120
            },
            gender: {
                required: false,
                type: 'string',
                enum: ['male', 'female', 'other']
            },
            status: {
                required: false,
                type: 'string',
                enum: ['active', 'inactive', 'suspended']
            }
        };

        // 登录验证规则
        this.loginRules = {
            email: {
                required: true,
                type: 'email'
            },
            password: {
                required: true,
                type: 'string',
                minLength: 1
            }
        };

        // 密码重置验证规则
        this.passwordResetRules = {
            email: {
                required: true,
                type: 'email'
            }
        };

        // 密码更新验证规则
        this.passwordUpdateRules = {
            current_password: {
                required: true,
                type: 'string'
            },
            new_password: {
                required: true,
                type: 'string',
                minLength: 6,
                maxLength: 128,
                custom: (value) => {
                    if (value && !/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
                        return 'Password must contain at least one lowercase letter, one uppercase letter, and one number';
                    }
                    return true;
                }
            },
            confirm_password: {
                required: true,
                type: 'string',
                custom: (value, data) => {
                    if (value !== data.new_password) {
                        return 'Password confirmation does not match';
                    }
                    return true;
                }
            }
        };

        // 数据转换规则
        this.transformRules = {
            username: 'trim',
            email: (value) => value.trim().toLowerCase(),
            full_name: 'trim',
            phone: 'trim',
            age: 'number',
            gender: 'lowercase',
            status: 'lowercase'
        };
    }

    /**
     * 验证用户创建数据
     * @returns {Object} - 验证结果
     */
    validateForCreate() {
        this.setValidationRules(this.createRules);
        this.setTransformRules(this.transformRules);
        return this.validateAndTransform();
    }

    /**
     * 验证用户更新数据
     * @returns {Object} - 验证结果
     */
    validateForUpdate() {
        this.setValidationRules(this.updateRules);
        this.setTransformRules(this.transformRules);
        return this.validateAndTransform();
    }

    /**
     * 验证登录数据
     * @returns {Object} - 验证结果
     */
    validateForLogin() {
        this.setValidationRules(this.loginRules);
        this.setTransformRules({ email: (value) => value.trim().toLowerCase() });
        return this.validateAndTransform();
    }

    /**
     * 验证密码重置数据
     * @returns {Object} - 验证结果
     */
    validateForPasswordReset() {
        this.setValidationRules(this.passwordResetRules);
        this.setTransformRules({ email: (value) => value.trim().toLowerCase() });
        return this.validateAndTransform();
    }

    /**
     * 验证密码更新数据
     * @returns {Object} - 验证结果
     */
    validateForPasswordUpdate() {
        this.setValidationRules(this.passwordUpdateRules);
        return this.validateAndTransform();
    }

    /**
     * 获取用于数据库存储的安全数据（排除敏感字段）
     * @param {boolean} includePassword - 是否包含密码字段
     * @returns {Object} - 安全的数据对象
     */
    getSafeData(includePassword = false) {
        const safeData = this.getCleanData();
        
        // 移除敏感字段
        if (!includePassword) {
            delete safeData.password;
            delete safeData.current_password;
            delete safeData.new_password;
            delete safeData.confirm_password;
        }
        
        return safeData;
    }

    /**
     * 获取用于API响应的公开数据（排除所有敏感字段）
     * @returns {Object} - 公开的数据对象
     */
    getPublicData() {
        const publicData = this.getSafeData(false);
        
        // 可以根据需要进一步过滤字段
        const allowedPublicFields = ['id', 'username', 'email', 'full_name', 'age', 'gender', 'status', 'created_at', 'updated_at'];
        const filteredData = {};
        
        for (const field of allowedPublicFields) {
            if (publicData[field] !== undefined) {
                filteredData[field] = publicData[field];
            }
        }
        
        return filteredData;
    }

    /**
     * 静态方法：验证用户创建数据
     * @param {Object} data - 用户数据
     * @returns {Object} - 验证结果
     */
    static validateCreate(data) {
        const dto = new UserDTO(data);
        return dto.validateForCreate();
    }

    /**
     * 静态方法：验证用户更新数据
     * @param {Object} data - 用户数据
     * @returns {Object} - 验证结果
     */
    static validateUpdate(data) {
        const dto = new UserDTO(data);
        return dto.validateForUpdate();
    }

    /**
     * 静态方法：验证登录数据
     * @param {Object} data - 登录数据
     * @returns {Object} - 验证结果
     */
    static validateLogin(data) {
        const dto = new UserDTO(data);
        return dto.validateForLogin();
    }

    /**
     * 静态方法：验证密码重置数据
     * @param {Object} data - 密码重置数据
     * @returns {Object} - 验证结果
     */
    static validatePasswordReset(data) {
        const dto = new UserDTO(data);
        return dto.validateForPasswordReset();
    }

    /**
     * 静态方法：验证密码更新数据
     * @param {Object} data - 密码更新数据
     * @returns {Object} - 验证结果
     */
    static validatePasswordUpdate(data) {
        const dto = new UserDTO(data);
        return dto.validateForPasswordUpdate();
    }
}

export default UserDTO;
